package com.quartet.modules.stock.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quartet.api.MapServerException;
import com.quartet.api.ResultErrorEnum;
import com.quartet.modules.stock.dao.TFlowCardStockDao;
import com.quartet.modules.stock.entity.TFlowCardStock;
import com.quartet.modules.stock.service.TFlowCardStockService;
import com.quartet.utils.StringUtils;
import com.quartet.utils.enums.ActiveStatusEnum;
import com.quartet.utils.enums.InventoryStatusEnum;
import com.quartet.utils.enums.OperatorsEnum;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 流量卡库存表(TFlowCardStock)表服务实现类
 *
 * @author makejava
 * @since 2021-06-20 09:07:33
 */
@Service("tFlowCardStockService")
public class TFlowCardStockServiceImpl extends ServiceImpl<TFlowCardStockDao, TFlowCardStock> implements TFlowCardStockService {

    /**
     *  批量导入流量卡库存信息
     * @param file
     * @throws IOException
     */
    @Override
    public void batchImportFlowCardStock(MultipartFile file) throws IOException {
        //获取Excel文件名称
        String originalFilename = file.getOriginalFilename();
        //获取文件扩展名
        String substring = originalFilename.substring(originalFilename.indexOf(".") + 1);
        List<TFlowCardStock> tFlowCardStockList = null;
        //如果是xls文件进入
        if (substring.equals("xls")) {
            InputStream inputStream = file.getInputStream();
            HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
            HSSFSheet sheetAt = workbook.getSheetAt(0);
            tFlowCardStockList = getFlowCardStockList(sheetAt);

        }

        //如果是xlsx文件进入
        if (substring.equals("xlsx")) {
            InputStream inputStream = file.getInputStream();
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            XSSFSheet sheetAt = workbook.getSheetAt(0);
            tFlowCardStockList = getFlowCardStockList(sheetAt);
        }
        this.saveBatch(tFlowCardStockList);
    }

    /**
     * 批量导出流量卡库存信息
     * @param response
     * @param idList
     * @throws IOException
     */
    @Override
    public void batchExportFlowCardStock(HttpServletResponse response, List<Integer> idList) throws IOException {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        QueryWrapper<TFlowCardStock> queryWrapper = new QueryWrapper<>();
        if (!CollectionUtils.isEmpty(idList)) {
            queryWrapper.lambda().in(TFlowCardStock::getId, idList);
        }
        List<TFlowCardStock> tFlowCardStockList = this.baseMapper.selectList(queryWrapper);
        //将javaBean转到excel中
        //創建一個workbook
        Workbook wrkbook = new XSSFWorkbook();
        //在workbook中創建一個Sheet
        Sheet sheet = wrkbook.createSheet();
        //添加表頭行
        Row row = sheet.createRow(0);
        //創建單元格
        Cell cell = row.createCell(0);
        cell.setCellValue("流量卡号");
        cell = row.createCell(1);
        cell.setCellValue("运营商");
        cell = row.createCell(2);
        cell.setCellValue("入库时间");
        cell = row.createCell(3);
        cell.setCellValue("出库时间");
        cell = row.createCell(4);
        cell.setCellValue("库存状态");
        //寫入實體數據
        int s = 1;
        for (TFlowCardStock tFlowCardStock : tFlowCardStockList) {
            row = sheet.createRow(s);
            row.createCell(0).setCellValue(tFlowCardStock.getFlowCardNumber());
            //考虑国际化
            row.createCell(1).setCellValue(tFlowCardStock.getOperators());
            row.createCell(2).setCellValue(df.format(tFlowCardStock.getStorageTime()));
            row.createCell(3).setCellValue(tFlowCardStock.getDeliveryTime() == null ? "" : df.format(tFlowCardStock.getDeliveryTime()));
            row.createCell(4).setCellValue(ActiveStatusEnum.find(tFlowCardStock.getInventoryStatus()).getDescription());
            s++;
        }
        //輸出excel文件
        OutputStream os = response.getOutputStream();
        BufferedOutputStream bs = new BufferedOutputStream(os);
        //清除空白行
        response.reset();
        response.setHeader("Content-disposition", "attachment;filename=" + new Date().getTime() + ".xlsx");
        response.setContentType("application/msexcel");
        wrkbook.write(bs);
        os.close();
    }

    /**
     * 解析sheet成javaBean
     *
     * @param sheet
     * @return
     */
    private List<TFlowCardStock> getFlowCardStockList(Sheet sheet) {
        List<TFlowCardStock> tFlowCardStockList = new ArrayList<>();
        List<String> flowCardCodeList = new ArrayList<>();
        //第一行是列名所以不读 获取第一行的下标 下标从0开始
        int firstRowIndex = sheet.getFirstRowNum() + 1;
        //获取最后一行的下标
        int lastRowIndex = sheet.getLastRowNum();
        //循环每一行
        for (int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {
            //获取某一行的数据
            Row row = sheet.getRow(rIndex);
            //如果该行不等于空
            if (row != null) {
                //获取某一行的第一个单元格的下标  下标从1开始
                int firstCellIndex = row.getFirstCellNum();
                //获取某一行的最后一个单元格的下标
                int lastCellIndex = row.getLastCellNum();
                TFlowCardStock tFlowCardStock = new TFlowCardStock();
                for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) {
                    //获取某一格的数据
                    Cell cell = row.getCell(cIndex);
                    cell.setCellType(CellType.STRING);
                    switch (cIndex) {
                        case 0: {
                            tFlowCardStock.setFlowCardNumber(cell.getStringCellValue());
                            break;
                        }
                        case 1: {
                            String value = cell.getStringCellValue();
//                            if (!OperatorsEnum.getValues().contains(value)) {
//                                throw new MapServerException(ResultErrorEnum.BMKPL003);
//                            }
                            tFlowCardStock.setOperators(value);
                            break;
                        }
                    }
                }
                QueryWrapper<TFlowCardStock> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(TFlowCardStock::getFlowCardNumber, tFlowCardStock.getFlowCardNumber());
                List<TFlowCardStock> list = this.baseMapper.selectList(queryWrapper);
                if (!CollectionUtils.isEmpty(list)) {
                    throw new MapServerException(ResultErrorEnum.BMKPL001);
                }
                if (flowCardCodeList.contains(tFlowCardStock.getFlowCardNumber())) {
                    throw new MapServerException(ResultErrorEnum.BMKPL002);
                }
                if (StringUtils.isBlank(tFlowCardStock.getOperators())) {
                    throw new MapServerException(ResultErrorEnum.BMKPL003);
                }
                tFlowCardStock.setStorageTime(LocalDateTime.now());
                tFlowCardStock.setInventoryStatus(InventoryStatusEnum.UNALLOCATED.getValue());
                tFlowCardStockList.add(tFlowCardStock);
                flowCardCodeList.add(tFlowCardStock.getFlowCardNumber());
            }
        }
        return tFlowCardStockList;
    }
}
